<template>
  <div class="app-container" id="AllPage">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:result_personal:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-printer"
          size="mini"
          v-hasPermi="['system:result_personal:export']"
          v-print="print"
        >打印</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-back"
          size="mini"
          @click="outerTest"
        >返回</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-row>
      <el-col>
        <div class="letter-opening">《{{result_personalList.scaleTitleShow}}》测评报告</div>
      </el-col>
      <el-col>
        <el-descriptions class="center" title="基本信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              登录名
            </template>
            {{result_personalList.loginName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              姓名
            </template>
            {{result_personalList.userName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              部门
            </template>
            {{result_personalList.deptName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              完成时间
            </template>
            {{result_personalList.createTime}}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>

      <el-col>
        <el-descriptions class="center" title="一、测验简介"  direction="vertical">
          <el-descriptions-item v-if="result_personalList.scale">
            {{result_personalList.scale.scaleDetails}}
          </el-descriptions-item>
        </el-descriptions>
      </el-col>

      <el-col>
        <div class="center">
            <div style="font-weight: bold;">二、测试结果:</div>
        </div>
        <div class="center">
          【总评】
        </div>
        <el-descriptions class="center" border>
          <el-descriptions-item>
            <template slot="label">
              原始分
            </template>
            {{result_personalList.countScore}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              标准分
            </template>
            {{earlyWarningScore}}
          </el-descriptions-item>
        </el-descriptions>
        <div class="center">【因子分数对应的结果提示】</div>
        <el-table class="center" :data="parsedScore" border>
          <el-table-column label="因子" width="180">
            <template slot-scope="{ row }">
              {{ row.factorName }}
            </template>
          </el-table-column>
          <el-table-column label="分数" width="180">
            <template slot-scope="{ row }">
              {{ row.score }}
            </template>
          </el-table-column>
          <el-table-column label="结果提示">
            <template slot-scope="{ row }">
              {{ row.description }}
            </template>
          </el-table-column>
          <el-table-column label="心理建议">
            <template slot-scope="{ row }">
              {{ row.heart }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col>
        <div class="center">
            <div style="font-weight: bold;">三、评语:</div>
        </div>
        <div class="center">
          <el-input
          type="textarea"
          :rows="5"
          v-model="result_personalList.scaleComments"
          :disabled="roleName === '学生'">
          </el-input>
        </div>
        <div class="center">
          <el-button type="primary" plain @click="handleAdd"
          v-hasPermi="['system:personScore:add']"
          v-if="roleName !== '学生'">新增</el-button>
        </div>
      </el-col>

      <el-col>
        <div class="center">
          <div style="font-weight: bold;">原始答卷</div>
        </div>
        <el-table class="center" :data="userAnswerList" border v-if="userAnswerList.length > 0">
          <el-table-column label="题目">
            <template slot-scope="{ row }">
              {{ row.question }}
            </template>
          </el-table-column>
          <el-table-column label="选项">
            <template slot-scope="{ row }">
              {{ row.answer }}
            </template>
          </el-table-column>
        </el-table>
        <p v-else class="center">暂无数据</p>
      </el-col>
    </el-row>
    
  </div>
</template>

<script>
import { listResult_personal, getResult_personal, delResult_personal, addResult_personal, updateResult_personal } from "@/api/mentalTest/personScore.js";
import { getInfo } from "@/api/login";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import Print from 'vue-print-nb';
import Vue from "vue";
Vue.use(Print);

export default {
  name: "report",
  data() {
    let that = this
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个人测评成绩报告表格数据
      result_personalList: {},
      //对应的量表信息
      scaleList:null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      resultId:null,
      earlyWarningScore:null,
      //解析factorScore为对象
      parsedScore : [],
      //解析factorResult为对象
      parsedResult: {},
      userAnswerList:[],
      //判断登录者的身份
      roleName:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scaleId: null,
        scaleTitleShow: null,
        userId: null,
        loginName: null,
        userName: null,
        countScore: null,
        factorScore: null,
        resultContent: null,
        factorResult: null,
        userAnswer: null,
        classesName: null,
        deptName: null,
        createTime:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      print: {
        id: 'AllPage',
        // popTitle: '配置页眉标题', // 打印配置页上方的标题
        // extraHead: '打印', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        // preview: true, // 是否启动预览模式，默认是false
        // previewTitle: '预览的标题', // 打印预览的标题
        // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback () { console.log('正在加载预览窗口！'); console.log(that.msg, this) }, // 预览窗口打开之前的callback
        previewOpenCallback () { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
        beforeOpenCallback () { console.log('开始打印之前！') }, // 开始打印之前的callback
        openCallback () { console.log('执行打印了！') }, // 调用打印时的callback
        closeCallback () { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted () { console.log('点击v-print绑定的按钮了！') },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: '',
        extarCss: ''
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.getRole();
  },
  computed: {
    
  },
  methods: {
    //获取路由参数
    getRouterQuery () {
        this.resultId = this.$router.history.current.query.resultId
        this.earlyWarningScore = this.$router.history.current.query.earlyWarningScore
    },
    /** 查询对应的测评成绩报告列表 */
    getList() {
      this.loading = true;
      this.getRouterQuery();
      // console.log("结果Id",this.resultId);
      // console.log("预警分数",this.earlyWarningScore);
      getResult_personal(this.resultId).then(response => {
        console.log("response.data",response.data);
        this.result_personalList = response.data;
        // 解析 factorScore 为对象
        // console.log("factorScore",this.result_personalList.factorScore);
        const scorePairs = this.result_personalList.factorScore.split("\n");
        for (const pair of scorePairs) {
          const trimmedPair = pair.trim(); // 去除两侧的空格
          if (trimmedPair) {
            const [factor, value] = trimmedPair.split(" = "); // 使用 " = " 分隔因子和值
            const factorName = factor.trim(); // 去除因子名称两侧的空格
            const score = parseFloat(value.trim()); // 解析值为浮点数
            // this.parsedScore[factorName] = factorValue; // 将因子和值添加到对象中
            // this.parsedScore.push({ factorName, score });
            const tempObject = { factorName, score };
            this.parsedScore.push(tempObject);
          }
        }
        // console.log("parsedScore",this.parsedScore);
        // 解析 factorResult 为对象
        // console.log("factorResult",this.result_personalList.factorResult);
        const resultPairs = this.result_personalList.factorResult.split("?<>");
        // console.log("resultPairs",resultPairs);
        let i = 0;
        let j = 0;
        for (const pair of resultPairs) {
          const trimmedPair = pair.trim();
          const trimmedpair1 = trimmedPair.split("$%^&");
          // console.log("trimmedpair1",trimmedpair1);
          if (trimmedpair1 && trimmedpair1 != "") {
            const sc = this.parsedScore[i++].score;
            // console.log("分数",sc);
            let flag = true;
            for(const line of trimmedpair1){
              // console.log("line",line);
              const [range, jieguo] = line.split('@#$%');
              const [min, max] = range.split('!@#$');
              const [description, heart] = jieguo.split('#$%^');
              // console.log("min",min);
              // console.log("max",max);
              // console.log("description",description);
              if(sc >= min && sc <= max){
                this.parsedScore.push({ ...this.parsedScore[j], description,heart });
                flag = false;
                break;
              }
            }
            if(flag){
              const heart = "暂无心理意见";
              const description = "暂无意见";
              this.parsedScore.push({ ...this.parsedScore[j], description,heart });
            }
            flag = true;
            j++;
          }
        }
        const len = Math.floor(this.parsedScore.length/2);
        // console.log("len",len);
        this.parsedScore.splice(0,len);
        this.formattedAnswers();
        this.total = response.total;
        this.loading = false;
        // console.log("简介",this.result_personalList.scale.scaleDetails);
      });
    },
    formattedAnswers() {
      if(this.result_personalList.userAnswer){
        console.log("userAnswer",this.result_personalList.userAnswer);
        const lines = this.result_personalList.userAnswer.split("\n");
        for(const line of lines){
          const [question, answer] = line.split("：");
          this.userAnswerList.push({question,answer})
        }
        if (this.userAnswerList.length > 0 
          && this.userAnswerList[this.userAnswerList.length - 1].question === "") {
          console.log("7777");
          this.userAnswerList.pop();
        }
      }else{
          this.userAnswerList = [];
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resultId: null,//测评结果id
        scaleId: null,//测评量表id
        scaleTitleShow: null,//测评量表名称
        userId: null,//用户id
        loginName: null,//登录账号
        userName: null,//用户昵称
        countScore: null,//总分
        factorScore: null,//因子的分数
        resultContent: null,//分数范围和结果提示
        factorResult: null,//因子的分数范围及结果提示
        userAnswer: null,//用户选择数据
        createTime: null,//创建时间
        updateTime: null,//更新修改时间
        classesName: null,//班级
        deptName: null//学院
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.resultId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //获取登录者的身份
    getRole(){
      getInfo().then(response =>{
        console.log("身份",response.user.roles[0].roleName);
        this.roleName = response.user.roles[0].roleName;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log("result_personalList",this.result_personalList);
      updateResult_personal(this.result_personalList).then(response => {
        this.$modal.msgSuccess("添加评语成功");
        this.open = false;
        this.getList();
      });
    },
    //因子分数对应分数范围得到结果提示
    getResult(score) {
      // 解析 factorResult 为对象
      console.log("factorResult",this.result_personalList.factorResult);
      const resultPairs = this.result_personalList.factorResult.split(";");
      console.log("resultPairs",resultPairs);
      for (const pair of resultPairs) {
        const trimmedpair = pair.trim();
        // const trimmedpair1 = trimmedpair.replace(/\n/g, "");
        // console.log("trimmedpair1",trimmedpair1);
        if (trimmedpair) {
          const trimmedpair1 = trimmedpair.split("\n");
          console.log("trimmedpair1",trimmedpair1);

          // const [range, description] = trimmedpair1.split(":");
          // const [min, max] = range.split("-");
          // this.parsedResult[min.trim()] = description.trim();
          // this.parsedResult[max.trim()] = description.trim();
          // console.log("parsedResult",this.parsedResult);

        }
      }
      // console.log("解析好的factorResult对象",this.parsedResult);
      // 根据分数获取对应的内容
      // for (const range in this.parsedResult) {
      //   if (score >= parseFloat(range)) {
      //     return this.parsedResult[range];
      //   }
      // }
      return "未知内容";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const resultId = row.resultId || this.ids
      getResult_personal(resultId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改个人测评成绩报告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.resultId != null) {
            updateResult_personal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResult_personal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const resultIds = row.resultId || this.ids;
      this.$modal.confirm('是否确认删除个人测评成绩报告编号为"' + resultIds + '"的数据项？').then(function() {
        return delResult_personal(resultIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const contentElement = document.querySelector(".app-container");

      // Use html2canvas to capture the content as an image
      html2canvas(contentElement).then((canvas) => {
      const imgData = canvas.toDataURL("image/jpeg");
      const pdf = new jsPDF();

      const imgWidth = 210; // A4 width in mm
      const imgHeight = (canvas.height * imgWidth) / canvas.width;

      let position = 0;
      let pageHeight = imgHeight;

      // Add content to PDF in chunks, creating new pages as needed
      while (position < canvas.height) {
      const chunkHeight = Math.min(pageHeight, canvas.height);
      pdf.addImage(
        imgData,
        "JPEG",
        0,
        0,
        imgWidth,
        chunkHeight,
        "",
        "FAST"
      );
      position += chunkHeight;

      // If there's more content, add a new page
      // if (position < canvas.height) {
      //   pdf.addPage();
      // }
      }

      // Save the PDF file
      pdf.save("个人报告.pdf");
      });
    },
    /** 打印按钮操作 */
    // handleExport1() {
    //   this.$modal.confirm('确认打印该危机预警信息吗？').then(response => {
    //     this.download('system/result_personal/export', {
    //       ...this.queryParams
    //     }, `result_personal_${new Date().getTime()}.pdf`)
    //   })
    // },
    // 返回路由跳转
    outerTest () {
      this.$router.push({
        path: '/mentalTest/personScore',
        query: {
        }
      })
    }
  }
}
</script>
<style>
.letter-opening {
  display: flex;
  justify-content: center;
  align-content: center;
  font-size: 26px;
  font-weight: bold;
}
.header-table {
    margin: 0 auto;
    border: 1px solid #e6ebf5;
    border-collapse: collapse;
    margin-top: 20px;
    width: 900px;
    height: 100px;
}
.header-table td{
    border: 1px solid #e6ebf5;
    text-align: center;
}
.tail-table{
    margin: 0 auto;
    border: 1px solid #e6ebf5;
    border-collapse: collapse;
    margin-top: 20px;
    width: 900px;
    height: 100px;
}
.tail-table td{
    border: 1px solid #e6ebf5;
    text-align: center;
}
.center {
    width: 900px;
    margin: 20px auto;
}
@page {
  margin: 0;
}
</style>

